﻿using MES_SystemUI.Context;
using MES_SystemUI.Domain;
using MES_SystemUI.Enumerate;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.Entity.Migrations;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

// MES_SystemUI.UI.DataDictUI.DataBaseForm
namespace MES_SystemUI.UI.DataDictUI
{
    public partial class DataBaseForm : MES_SystemUI.UI.DataForm
    {
        public string TableName = "";
        public DataBaseForm()
        {
            InitializeComponent();
            dataGridView1.CellPainting += DataGridView1_CellPainting;
            dataGridView1.CellMouseClick += DataGridView1_CellMouseClick;
            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = " ";
            dateTimePicker2.Format = DateTimePickerFormat.Custom;
            dateTimePicker2.CustomFormat = " ";
            dateTimePicker1.ValueChanged += DateTimePicker1_ValueChanged;
            dateTimePicker2.ValueChanged += DateTimePicker2_ValueChanged;
            button4.Click += Button4_Click;
            button3.Click += Button3_Click;
            button5.Click += Button5_Click;
            button6.Click += Button6_Click;
            comboBox1BingData();
        }
        // comboBox1绑定数据 -1 全部 0启用 1 禁用
        private void comboBox1BingData()
        {
            comboBox1.DataSource = new List<Enumerate.StatusEnum>() {
                StatusEnum.全部,
                StatusEnum.启用,
                StatusEnum.禁用,
            };
            comboBox1.SelectedIndex = 0;
        }

        // 重写 绑定数据
        public override void BindDataGridView()
        {
            // 获取总页数,每页十条数据
            GetDataBind();

            dataGridView1.Columns.Add("Edit", "操作");

            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
            dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            dataGridView1.Columns["Edit"].Width = 150;
            dataGridView1.Columns["序号"].Width = 70;
        }

        // 重写 获取数据的过程
        /// <summary>
        /// 关键的获取数据过程，根据表重写
        /// </summary>
        public virtual void GetDataBind()
        {
            //using (var ct = new Context.MES_SystemContext())
            //{
            //    var que = from Pc in ct.productCategories
            //              join U1 in ct.users on Pc.CreateUserId equals U1.UserId
            //              join U2 in ct.users on Pc.LastUpdateUserId equals U2.UserId into AllPc
            //              from pc in AllPc.DefaultIfEmpty()
            //              select new
            //              {
            //                  序号 = Pc.ProductCategoryId,
            //                  类型名称 = Pc.ProductCategoryName,
            //                  状态 = Pc.Status == 0 ? "启用" : "禁用",
            //                  创建人 = U1.UserName,
            //                  创建时间 = Pc.CreateTime,
            //                  最后修改人 = pc.UserName != null ? pc.UserName : null,
            //                  最后修改时间 = Pc.LastUpdateTime,
            //              };
            //    if (!string.IsNullOrEmpty(textBox1.Text.Trim()))
            //    {
            //        que = que.Where(x => Regex.IsMatch(x.类型名称, textBox1.Text));
            //    }
            //    if (!string.IsNullOrEmpty(dateTimePicker1.Text.Trim()))
            //    {
            //        //DateTime dateTime1 = DateTime.Parse(dateTimePicker1.Value.ToString("yyyy-MM-dd") + " 00:00:00");
            //        DateTime dateTime1 = DateTime.Parse(dateTimePicker1.Text + " 00:00:00");
            //        que = que.Where(x => x.创建时间 >= dateTime1);
            //    }
            //    if (!string.IsNullOrEmpty(dateTimePicker2.Text.Trim()))
            //    {
            //        //DateTime dateTime2 = DateTime.Parse(dateTimePicker2.Value.ToString("yyyy-MM-dd") + " 23:59:59");
            //        DateTime dateTime2 = DateTime.Parse(dateTimePicker2.Text + " 23:59:59");
            //        que = que.Where(x => x.创建时间 <= dateTime2);
            //    }
            //    if (comboBox1.Text != "全部")
            //    {
            //        que = que.Where(x => x.状态 == comboBox1.Text);
            //    }
            //    Page = que.Count();
            //    que = que.OrderByDescending(k => k.序号);
            //    que = que.Skip((NumberPage - 1) * MainForm.SystemDataConfig.pageNumber).Take(MainForm.SystemDataConfig.pageNumber);
            //    // 绑定数据
            //    dataGridView1.Columns.Clear();
            //    dataGridView1.DataSource = que.ToList();

                
            //}
        }

        // 导出
        private void Button6_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            // 保存工作簿到文件
            saveFileDialog.Filter = "Excel Files (*.xlsx)|*.xlsx";
            saveFileDialog.Title = "保存Excel";
            saveFileDialog.AddExtension = true;
            saveFileDialog.FileName = TableName+DateTime.Now.ToString("yyyyMMddHHmmss");
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("sheet1");
                IRow headerRow = sheet.CreateRow(0);
                for (int i = 0;i< dataGridView1.Columns.Count; i++)
                {
                    if (dataGridView1.Columns[i].Name == "Edit") continue;
                    headerRow.CreateCell(i).SetCellValue(dataGridView1.Columns[i].Name);
                }
                for (int i = 0; i< dataGridView1.Rows.Count; i++)
                {
                    IRow dataRow = sheet.CreateRow(i+1);
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        if (dataGridView1.Columns[j].Name == "Edit") continue;
                        dataRow.CreateCell(j).SetCellValue(dataGridView1.Rows[i].Cells[j].Value!= null? dataGridView1.Rows[i].Cells[j].Value .ToString():null);
                    }
                }
                if (saveFileDialog.FileName != "")
                {
                    using (FileStream fileStream = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        workbook.Write(fileStream);
                    }
                }
                // 关闭工作簿
                workbook.Close();
            }
        }

        // 导入
        private void Button5_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Excel Files (*.xlsx)|*.xlsx";
            openFileDialog.Title = "导入Excel";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                DataTable dt = MES_SystemUI.Helpers.DataTableOnExcel.ExcelToTable(openFileDialog.FileName);
                try
                {
                    using (var c = new Context.MES_SystemContext())
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            OpenExcelCore(dt, c, i);
                        }
                        c.SaveChanges();
                        BindDataGridView();
                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message+"\n"+ex.Source + "\n" + ex.InnerException.ToString().Split('。')[0], "导入失败", MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
                
            }
        }
        /// <summary>
        /// 导入Excel关键 ，重写
        /// </summary>
        /// <param name="dt">读取的Excel表</param>
        /// <param name="c">上下文</param>
        /// <param name="i">行</param>
        public virtual void OpenExcelCore(DataTable dt, MES_SystemContext c, int i)
        {
            //ProductCategorie mode = new ProductCategorie()
            //{
            //    ProductCategoryName = dt.Rows[i][0].ToString(),
            //    Status = int.Parse(dt.Rows[i][1].ToString()),
            //    CreateUserId = int.Parse(dt.Rows[i][2].ToString()),
            //};
            //c.productCategories.Add(mode);
        }

        // 查询
        private void Button3_Click(object sender, EventArgs e)
        {
            BindDataGridView();
        }
        // 重置
        private void Button4_Click(object sender, EventArgs e)
        {
            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = " ";
            dateTimePicker2.Format = DateTimePickerFormat.Custom;
            dateTimePicker2.CustomFormat = " ";
        }

        private void DateTimePicker2_ValueChanged(object sender, EventArgs e)
        {
            dateTimePicker2.Format = DateTimePickerFormat.Custom;
            dateTimePicker2.CustomFormat = "yyyy-MM-dd";
        }

        private void DateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            
            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = "yyyy-MM-dd";
        }

        // 单元格 重绘
        private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if(e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                if (dataGridView1.Columns[e.ColumnIndex].Name == "状态")
                {
                    if (e.Value.ToString() == "禁用")
                    {
                        e.CellStyle.ForeColor = Color.Red;
                    }
                    if (e.Value.ToString() == "启用")
                    {
                        e.CellStyle.ForeColor = Color.Green;
                    }
                }
                if (dataGridView1.Columns[e.ColumnIndex].Name == "Edit")
                {
                    // 设置 绘制范围内 水平居中对齐 垂直居中对齐
                    StringFormat stringFormat = new StringFormat();
                    stringFormat.Alignment = StringAlignment.Center;
                    stringFormat.LineAlignment = StringAlignment.Center;

                    //SizeF sizeFJY = e.Graphics.MeasureString("禁用",MainForm.SystemDataConfig.GlobalFont);
                    //SizeF sizeFQY =  e.Graphics.MeasureString("启用",MainForm.SystemDataConfig.GlobalFont);

                    RectangleF rectangleFCom = new RectangleF(e.CellBounds.X, e.CellBounds.Y, (float)e.CellBounds.Width * 0.5F, e.CellBounds.Height);
                    RectangleF rectangleFDel = new RectangleF(e.CellBounds.X + (float)e.CellBounds.Width * 0.5F, e.CellBounds.Y, (float)e.CellBounds.Width * 0.5F, e.CellBounds.Height);
                    e.PaintBackground(e.CellBounds, false);
                    e.Graphics.DrawString("禁用", MainForm.SystemDataConfig.GlobalFont, Brushes.Red, rectangleFCom, stringFormat);
                    e.Graphics.DrawString("启用", MainForm.SystemDataConfig.GlobalFont, Brushes.Blue, rectangleFDel, stringFormat);

                    e.Handled = true;
                }
            }
        }

        // 点击单元格
        public virtual void DataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                if (dataGridView1.Columns[e.ColumnIndex].Name == "Edit")
                {
                    Point point = e.Location;
                    Graphics g = dataGridView1.CreateGraphics();
                    SizeF sizeFCom = g.MeasureString("禁用", MainForm.SystemDataConfig.GlobalFont);
                    SizeF sizeFDel = g.MeasureString("启用", MainForm.SystemDataConfig.GlobalFont);
                    float aCom = (float)sizeFCom.Width / (sizeFCom.Width + sizeFDel.Width);
                    float bDel = (float)sizeFDel.Width / (sizeFCom.Width + sizeFDel.Width);
                    RectangleF rectangleF = new RectangleF(0, 0, dataGridView1.Columns[e.ColumnIndex].Width, dataGridView1.Rows[e.RowIndex].Height);
                    RectangleF rectangleFCom = new RectangleF(rectangleF.Left, rectangleF.Top, rectangleF.Width * aCom, rectangleF.Height);
                    RectangleF rectangleFDel = new RectangleF(rectangleFCom.Right, rectangleF.Top, rectangleF.Width * bDel, rectangleF.Height);
                    if (rectangleFCom.Contains(point))
                    {
                        if (dataGridView1.Rows[e.RowIndex].Cells["状态"].Value.ToString() == "禁用")
                        {
                            MessageBox.Show("已禁用");
                        }
                        else
                        {
                            using (var c = new Context.MES_SystemContext())
                            {
                                StateCore(e, c,1);
                                c.SaveChanges();
                            }
                        }
                        BindDataGridView();
                    }
                    else if (rectangleFDel.Contains(point))
                    {
                        if (dataGridView1.Rows[e.RowIndex].Cells["状态"].Value.ToString() == "启用")
                        {
                            MessageBox.Show("已启用");
                        }
                        else
                        {
                            using (var c = new Context.MES_SystemContext())
                            {
                                StateCore(e, c, 0);
                                c.SaveChanges();
                            }
                        }
                        BindDataGridView();
                    }
                }
            }
        }
        /// <summary>
        /// 修改状态核心，可重写。根据序号修改对应行数据状态
        /// </summary>
        /// <param name="e">选中单元格</param>
        /// <param name="c">上下文</param>
        /// <param name="state">设置状态</param>
        public virtual void StateCore(DataGridViewCellMouseEventArgs e, MES_SystemContext c,int state)
        {
            //var Pc = c.productCategories.Find(int.Parse(dataGridView1.Rows[e.RowIndex].Cells["序号"].Value.ToString()));
            //Pc.Status = state;
        }
    }
}
